package com.ruoyi.recycle.utils.debang;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.lang.StringUtils;

public class HttpUtils {
    public static final ResultDO<String> sendRequest(String url, List<Header> headerList, RequestEntity requestEntry, String encoding, int timeout) {
        if (StringUtils.isEmpty(url)) {
            return (new ResultDO<String>()).setException(new NullPointerException("url empty"));
        }

        if (null == requestEntry) {
            return (new ResultDO<String>()).setException(new NullPointerException("requestEntry empty"));
        }


        PostMethod postMethod = new PostMethod(url);
        postMethod.getParams().setContentCharset(encoding);
        postMethod.getParams().setHttpElementCharset(encoding);


        if (headerList != null) {
            for (Header header : headerList) {
                postMethod.addRequestHeader(header);
            }
        }


        postMethod.setRequestEntity(requestEntry);


        HttpClient httpClient = new HttpClient();
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);

        httpClient.getHttpConnectionManager().getParams().setSoTimeout(timeout);

        try {
            httpClient.executeMethod(postMethod);
            if (postMethod.getStatusCode() == 200) {
                return (new ResultDO<String>()).setModel(postMethod.getResponseBodyAsString());
            }

            return (new ResultDO<String>()).setException(new IllegalStateException("sendRequest remote error")).setModel(postMethod.getResponseBodyAsString());

        } catch (Exception e) {
            return (ResultDO) (new ResultDO()).setException(e);
        } finally {
            postMethod.releaseConnection();
        }
    }


    public static final ResultDO<String> sendRequest(String url, NameValuePair[] paramsList, String encoding, int timeout) {
        String tmpencoding = encoding;
        int tmptimeout = timeout;

        if (StringUtils.isEmpty(url)) {
            return (new ResultDO<String>()).setException(new NullPointerException("url empty"));
        }

        if (null == paramsList) {
            return (new ResultDO<String>()).setException(new NullPointerException("paramsList empty"));
        }

        if (StringUtils.isBlank(encoding)) {
            tmpencoding = "UTF-8";
        }
        if (timeout <= 0) {
            tmptimeout = 5000;
        }


        PostMethod postMethod = new PostMethod(url);
        postMethod.getParams().setContentCharset(tmpencoding);
        postMethod.getParams().setHttpElementCharset(tmpencoding);


        postMethod.setRequestBody(paramsList);


        HttpClient httpClient = new HttpClient();
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(tmptimeout);

        httpClient.getHttpConnectionManager().getParams().setSoTimeout(tmptimeout);

        try {
            httpClient.executeMethod(postMethod);
            if (postMethod.getStatusCode() == 200) {
                return (new ResultDO<String>()).setModel(postMethod.getResponseBodyAsString());
            }

            return (new ResultDO<String>()).setException(new IllegalStateException("sendRequest remote error")).setModel(postMethod.getResponseBodyAsString());

        } catch (Exception e) {
            return (ResultDO) (new ResultDO()).setException(e);
        } finally {
            postMethod.releaseConnection();
        }
    }


    public static final String postHttp(String url, String params, String encoding) throws UnsupportedEncodingException {
        String responseMsg = "";

        HttpClient httpClient = new HttpClient();

        httpClient.getParams().setContentCharset(encoding);

        PostMethod postMethod = new PostMethod(url);
        InputStream requestIO = new ByteArrayInputStream(params.getBytes("UTF-8"));

        InputStreamRequestEntity entity = new InputStreamRequestEntity(requestIO);

        postMethod.setRequestEntity(entity);

        try {
            httpClient.executeMethod(postMethod);

            responseMsg = postMethod.getResponseBodyAsString();
        } catch (HttpException e) {
            e.printStackTrace();
            throw new UnsupportedEncodingException(e.getClass().getName());
        } catch (IOException e) {
            e.printStackTrace();
            throw new UnsupportedEncodingException(e.getClass().getName());
        } finally {

            postMethod.releaseConnection();
        }
        return responseMsg;
    }


    public static final String postHttp(String url, String params) throws UnsupportedEncodingException {
        String responseMsg = "";

        HttpClient httpClient = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true));
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(10000);

        httpClient.getParams().setContentCharset("UTF-8");

        PostMethod postMethod = new PostMethod(url);

        postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");


        postMethod.setRequestBody(params);
        postMethod.setRequestHeader("Connection", "close");

        try {
            httpClient.executeMethod(postMethod);

            responseMsg = postMethod.getResponseBodyAsString();
        } catch (HttpException e) {
            e.printStackTrace();
            throw new UnsupportedEncodingException(e.getClass().getName());
        } catch (IOException e) {
            e.printStackTrace();
            throw new UnsupportedEncodingException(e.getClass().getName());
        } finally {

            postMethod.releaseConnection();
            httpClient.getHttpConnectionManager().closeIdleConnections(0L);
        }
        return responseMsg;
    }


    public static final String post(String url, String params, int timeout) throws IOException {
        String responseMsg = "";

        HttpClient httpClient = new HttpClient();

        httpClient.getParams().setContentCharset("UTF-8");

        PostMethod postMethod = new PostMethod(url);

        postMethod.setRequestHeader("Content-Type", "application/json");

        if (timeout <= 0) {
            timeout = 5000;
        }


        postMethod.getParams().setParameter("http.protocol.content-charset", "UTF-8");
        RequestEntity requestEntity = new StringRequestEntity(params, "application/json", "UTF-8");
        postMethod.setRequestEntity(requestEntity);

        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(timeout);


        try {
            httpClient.executeMethod(postMethod);

            responseMsg = postMethod.getResponseBodyAsString();
        } catch (HttpException e) {
            e.printStackTrace();
            throw new HttpException(e.getClass().getName());
        } catch (IOException e) {
            e.printStackTrace();
            throw new IOException(e.getClass().getName());
        } finally {

            postMethod.releaseConnection();
        }
        return responseMsg;
    }


    public static synchronized String postData(String url, Map<String, String> params, String codePage) throws IOException {
        HttpClient httpClient = new HttpClient();
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(60000);


        httpClient.getHttpConnectionManager().getParams().setSoTimeout(60000);


        PostMethod method = new PostMethod(url);
        if (params != null) {
            method.getParams().setParameter("http.protocol.content-charset", codePage);

            method.setRequestBody(assembleRequestParams(params));
        }
        String result = "";
        try {
            httpClient.executeMethod(method);
            result = new String(method.getResponseBody(), codePage);
        } catch (IOException e) {
            throw e;
        } finally {
            method.releaseConnection();
        }
        return result;
    }


    public static synchronized String postDataRequestBody(String url, String params, String codePage) throws IOException {
        HttpClient httpClient = new HttpClient();
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);


        httpClient.getHttpConnectionManager().getParams().setSoTimeout(5000);


        PostMethod method = new PostMethod(url);
        if (params != null) {
            method.getParams().setParameter("http.protocol.content-charset", codePage);

            method.setRequestBody(params);
        }
        String result = "";
        try {
            httpClient.executeMethod(method);
            result = new String(method.getResponseBody(), codePage);
        } catch (IOException e) {
            throw e;
        } finally {
            method.releaseConnection();
        }
        return result;
    }


    public static String postHttp(String url, NameValuePair[] data) {
        HttpClient httpClient = new HttpClient();

        httpClient.getParams().setContentCharset("utf-8");

        PostMethod postMethod = new PostMethod(url);


        postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

        postMethod.setRequestBody(data);

        StringBuffer stringBuffer = new StringBuffer();
        try {
            httpClient.executeMethod(postMethod);
            InputStream inputStream = postMethod.getResponseBodyAsStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
            String str = "";
            while ((str = br.readLine()) != null) {
                stringBuffer.append(str);
            }
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            postMethod.releaseConnection();
        }
        return stringBuffer.toString();
    }


    public static String httpClient(String url, String params, String chartSet) {
        String jsonResponse = "";

        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(url);

        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        method.getParams().setContentCharset(chartSet);
        method.getParams().setHttpElementCharset(chartSet);


        try {
            System.out.println("请求发出前消息：" + params);

            RequestEntity entity = null;
            entity = new StringRequestEntity(params, "application/json", "UTF-8");

            method.setRequestEntity(entity);
            method.addRequestHeader("Content-Type", "application/json;charset=UTF-8");
            int statuCode = client.executeMethod(method);
            jsonResponse = method.getResponseBodyAsString();
            System.out.println("响应消息：" + jsonResponse);
            if (statuCode == 200) {
                System.out.println("response is ok!");
            }
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return jsonResponse;
    }


    public static String sendPostRequest(String urlStr, String params) {
        String data = params;
        String response = "";


        try {
            URL url = new URL(urlStr);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());


            writer.write(data);
            writer.flush();


            StringBuffer answer = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                answer.append(line);
            }
            writer.close();
            reader.close();


            response = answer.toString();
            System.out.println("菜鸟异常响应：" + response);
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        return response;
    }


    public static String getJstHttpResult(String urlStr, String content) {
        URL url = null;
        HttpURLConnection connection = null;

        try {
            url = new URL(urlStr);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.connect();

            DataOutputStream out = new DataOutputStream(connection.getOutputStream());

            out.write(content.getBytes("utf-8"));
            out.flush();
            out.close();

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));


            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            reader.close();
            return buffer.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }

        return null;
    }


    public static String sendGetRequest(String url, String charset) {
        HttpClient httpClient = new HttpClient();

        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        GetMethod getMethod = new GetMethod(url);

        getMethod.getParams().setParameter("http.socket.timeout", Integer.valueOf(5000));

        getMethod.getParams().setParameter("http.method.retry-handler", new DefaultHttpMethodRetryHandler());
        String response = "";

        try {
            int statusCode = httpClient.executeMethod(getMethod);

            if (statusCode != 200) {
                System.out.println("请求出错: " + getMethod.getStatusLine());
            }

            byte[] responseBody = getMethod.getResponseBody();
            response = new String(responseBody, charset);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            getMethod.releaseConnection();
        }
        return response;
    }


    private static synchronized NameValuePair[] assembleRequestParams(Map<String, String> data) {
        List<NameValuePair> nameValueList = new ArrayList<NameValuePair>();

        Iterator<Map.Entry<String, String>> it = data.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> entry = it.next();

            nameValueList.add(new NameValuePair(entry.getKey(), entry.getValue()));
        }


        return nameValueList.<NameValuePair>toArray(new NameValuePair[nameValueList.size()]);
    }
}
